package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2021-05-29
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {

    @Autowired
    private IApBehaviorEntryService iApBehaviorEntryService;

    @Override
    public void saveBehavior(FollowBehaviorDto dto) {
        //查询实体
        EntryDto entryDto = new EntryDto(dto.getEquipmentId(),dto.getUserId());
        ApBehaviorEntry entry = iApBehaviorEntryService.getEntry(entryDto);

        LambdaQueryWrapper<ApFollowBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApFollowBehavior::getEntryId,entry.getId());
        query.eq(ApFollowBehavior::getFollowId,dto.getFollowId());
        ApFollowBehavior followBehavior = this.getOne(query);
        if (followBehavior != null){
            if (followBehavior.getOperation() != dto.getOperation()){
                followBehavior.setOperation(dto.getOperation());
                this.updateById(followBehavior);
            }
           }else {
            //构建对象
            ApFollowBehavior apFollowBehavior = new ApFollowBehavior();
            apFollowBehavior.setEntryId(entry.getId());
            apFollowBehavior.setFollowId(dto.getFollowId());
            apFollowBehavior.setOperation(dto.getOperation());
            apFollowBehavior.setCreatedTime(new Date());
            this.save(apFollowBehavior);
        }
    }
}
